package com.heima.gateway.filter;

import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * 拦截所有请求，获取token，刷新token
 */
@Component
@Order(-100)
@RequiredArgsConstructor
public class RefreshfFilter implements GlobalFilter {
    private final StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        //没有token
        if(token == null){
            return chain.filter(exchange);
        }
        //有token
        //2.验证token
        String userId = redisTemplate.opsForValue().get("login_user_token:" + token);
        if(userId == null){
           return chain.filter(exchange);
        }
        //3.刷新token
        redisTemplate.expire("login_user_token:" + token, 60 , TimeUnit.MINUTES);
        return chain.filter(exchange);
    }
}
